package com.atguigu.gulimall.order.config;

import com.zaxxer.hikari.HikariDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * @create: 2024/9/13
 * @author: gyhe10
 * @description: seata 实现分布式事务相关配置
 **/
@Configuration
public class MySeataConfig {

    /**
     * 可以省略
     * 因为 DataSourceProperties 已经在数据源自动配置类 DataSourceAutoConfiguration 中通过 @EnableConfigurationProperties(DataSourceProperties.class) 注解注入到 Spring 容器
     * Spring 配置类中的 @Bean 方法可以直接使用 Spring 容器中的 Bean 作为参数
     */
    @Resource
    private DataSourceProperties dataSourceProperties;

    @Bean
    public DataSource dataSource(DataSourceProperties dataSourceProperties){
        HikariDataSource hikariDataSource = dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
        if (StringUtils.hasText(dataSourceProperties.getName())) {
            hikariDataSource.setPoolName(dataSourceProperties.getName());
        }
        return new DataSourceProxy(hikariDataSource);
    }
}
